package com.xr.blackhoole.mock.utils;

import com.xr.blackhoole.mock.WormholeMockCallback;
import com.xr.blackhoole.mock.annotation.WormholeMock;
import com.xr.blackhoole.mock.strategy.DefautlWormholeMockCallback;
import com.xr.blackhoole.mvc.reflect.WormholeReflectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WormholeMockUtils {

    private static final Map<String, WormholeMockCallback> mockCallbackMap = new ConcurrentHashMap<>();


    /**
     * 获取方法的注解对象
     *
     * @param joinPoint
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T extends Annotation> T getMethodAnnotation(JoinPoint joinPoint, Class<T> clazz) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        return method.getAnnotation(clazz);
    }


    /**
     * 获取Mock的回调对象
     *
     * @param wormholeMock
     * @return
     */
    public static WormholeMockCallback getWormholeMockCallback(WormholeMock wormholeMock) {
        String wormholeMockSign = getWormholeMockSign(wormholeMock);
        if (StringUtils.isNotEmpty(wormholeMockSign) && null != wormholeMock.callback()) {
            return mockCallbackMap.computeIfAbsent(wormholeMockSign, k -> {
                WormholeMockCallback wormholeMockCallback = null;
                Object callbackObject = WormholeReflectUtils.generateObject(wormholeMock.callback());
                if (null != callbackObject && callbackObject instanceof WormholeMockCallback) {
                    wormholeMockCallback = (WormholeMockCallback) callbackObject;
                } else {
                    wormholeMockCallback = new DefautlWormholeMockCallback();
                }
                wormholeMockCallback.init(wormholeMock);
                return wormholeMockCallback;
            });
        }
        return null;
    }

    /**
     * 获取签名
     *
     * @param wormholeMock
     * @return
     */
    private static String getWormholeMockSign(WormholeMock wormholeMock) {
        if (null != wormholeMock) {
            return wormholeMock.callback().getName() + wormholeMock.passRate() + wormholeMock.minDelayTime() + wormholeMock.maxDelayTime();
        }
        return null;
    }
}
